package com.microframework.boot.visual.controller;

import java.sql.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson2.JSONObject;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.microframework.base.core.datasource.annotation.Tx;
import com.microframework.base.core.util.SecurityUtils;
import com.microframework.base.core.util.UuidUtil;
import com.microframework.base.web.page.PageQuery;
import com.microframework.base.web.resp.R;
import com.microframework.boot.fs.service.IMinioService;
import com.microframework.boot.visual.model.domain.Project;
import com.microframework.boot.visual.service.IProjectPageService;
import com.microframework.boot.visual.service.IProjectService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/visual/project")
@Tag(name = "项目接口管理", description = "可视化设计器项目接口管理相关接口")
public class ProjectController {

	@Autowired
	private IProjectService projectService;

	@Autowired
	private IProjectPageService projectPageServiceService;
	
	@Autowired
	private IMinioService minioService;
	
	private final String BUCKET_NAME = "visual";

	@PostMapping("/pages")
	@Operation(summary = "分页查询项目列表", description = "分页查询项目数据")
	public R<Page<Project>> pages(@RequestBody PageQuery<Project> pageQuery) {
		return R.ok(projectService.pages(pageQuery));
	}

	
	@Operation(summary = "保存组件")
	@Parameters({ @Parameter(name = "thumbnailFile", description = "缩略图", required = false),
	@Parameter(name = "project", description = "项目信息", required = true) })
	@PostMapping("/save")
	@Tx
	public R<Project> save(HttpServletRequest request, MultipartFile thumbnailFile,
			Project project) {
		try {
			if (StrKit.notBlank(project.getId())) {
				project.setModifyTime(new Date(System.currentTimeMillis()));
				project.setModifyUserId(SecurityUtils.getUserId());
				if (project.update()) {
					if (thumbnailFile != null) {
						String path = minioService.uploadFile(BUCKET_NAME, thumbnailFile, project.getId());
						project.setThumbnail(path+'.'+minioService.getFileExtension(thumbnailFile));
						project.update();
					}
					return R.ok(project);
				} else {
					return R.fail("更新失败！");
				}
			} else {
				project.setId(UuidUtil.getUUID());
				project.setCreateTime(new Date(System.currentTimeMillis()));
				project.setCreateUserId(SecurityUtils.getUserId());
				if (project.save()) {
					if (thumbnailFile != null) {
						String path = minioService.uploadFile(BUCKET_NAME, thumbnailFile, project.getId());
						project.setThumbnail(path+'.'+minioService.getFileExtension(thumbnailFile));
						project.update();
					}
					return R.ok(project);
				} else {
					return R.fail("保存失败.");
				}
			}
		} catch (Exception e) {
			return R.fail(e.getMessage());
		}
	}
	
	@Operation(summary = "删除项目")
	@Parameters({ @Parameter(name = "id", description = "项目id", required = true) })
	@DeleteMapping("/detain/{id}")
	@Tx
	public R<String> deleteUserById(@PathVariable("id") String id) {
		try {
			Project project = new Project();
			project.setId(id);
			project.setIsDel("1");
			if (project.update()) {
				return R.ok("删除成功.");
			} else {
				return R.fail("删除失败.");
			}
		} catch (Exception e) {
			log.error("删除用户异常:{}", e.getMessage());
			return R.fail(e.getMessage());
		}
	}

	@Operation(summary = "保存项目页面")
	@Parameters({ @Parameter(name = "id", description = "项目id", required = true),
			@Parameter(name = "pages", description = "项目页面", required = true) })
	@PostMapping("/{id}/pages/save")
	@Tx(value="micro_visual",useSavepoint = true, timeout = 60)
	public R<Project> updateAllPages(@PathVariable("id") String id, @RequestBody JSONObject pages) {
		try {
			projectPageServiceService.updateAllPages(id,pages);
			return R.ok();
		} catch (Exception e) {
			return R.fail(e.getMessage());
		}
	}
	
	@Operation(summary = "项目页面")
	@Parameters({ @Parameter(name = "id", description = "项目id", required = true) })
	@GetMapping("/{id}/pages")
	public R<JSONObject> getPagesByProjectId(@PathVariable("id") String id) {
		try {
			JSONObject pages=projectPageServiceService.getPagesByProjectId(id);
			return R.ok(pages);
		} catch (Exception e) {
			log.error("获取项目页面异常:{}", e.getMessage());
			return R.fail(e.getMessage());
		}
	}

}
